package com.ki.glasscase.svc.services.impl;

import com.ki.glasscase.svc.dao.ProductTagDAO;
import com.ki.glasscase.svc.dao.ProductDAO;
import com.ki.glasscase.svc.dao.TagDAO;
import com.ki.glasscase.svc.dto.ProductDTO;
import com.ki.glasscase.svc.entity.Product;
import com.ki.glasscase.svc.entity.Tag;
import com.ki.glasscase.svc.services.DownloadProperties;
import com.ki.glasscase.svc.services.ServiceImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by Khacheresyants.L on 2/18/14.
 */
@Service
public class ImplImportService implements ServiceImport {

    private HashMap<String, Long> tagCash = new HashMap<String, Long>();
    private Logger logger = Logger.getLogger("ImplImportService.class");
    @Autowired
    public DownloadProperties downloadProperties;
    @Autowired
    public ProductTagDAO productTagDAO;
    @Autowired
    public ProductDAO productDAO;
    @Autowired
    public TagDAO tagDAO;
    @Autowired
    public XMLParserSAX xmlParserSAX;
    @Autowired
    public ProductHandler productHandler;


    public void importXML() {
        File output = downloadProperties.getCurrentOS(System.getProperty("os.name"));
        Long start = new Date().getTime();
        downloadXML(downloadProperties.getUrl(), output);
        Long endLoad = new Date().getTime() - start;
        start = new Date().getTime();
        xmlParserSAX.parse(output.getAbsolutePath(), productHandler);
        Long endParse = new Date().getTime() - start;
        List<ProductDTO> list = productHandler.getProductDTOs();
        start = new Date().getTime();
        for (ProductDTO product : list) {
            createEntities(product);
        }
        Long endCreateOrUpdate = new Date().getTime() - start;
        logger.info(
                String.format("Time spent for download is %d ms, time parsing is %d ms, end input to DB is %d",
                        endLoad, endParse, endCreateOrUpdate));
    }

    private void createEntities(ProductDTO productDTO) {
        Product product = productDTO.getProduct();
        product.setId(productDAO.create(product));
        if (product.getId() != null) {
            ArrayList<Long> tags_id = new ArrayList<Long>();
            for (Tag tag : productDTO.getTag()) {
                Long id = null;
                if (tagCash.containsKey(tag.getName())) {
                   id = tagCash.get(tag.getName());
                } else {
                    id = tagDAO.create(tag);
                    tagCash.put(tag.getName(), id);
                }

                tags_id.add(id);
            }
            for (Long id : tags_id) {
                productTagDAO.create(product.getId(), id);
            }
        }
    }

    private void downloadXML(URL url, File outputFile) {
        InputStream conn = null;
        FileOutputStream fos = null;
        try {
            conn = url.openStream();
            fos = new FileOutputStream(outputFile);
            int length = -1;
            byte[] buffer = new byte[4128];
            while ((length = conn.read(buffer)) > -1) {
                fos.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
